package com.android.search;

import java.util.ArrayList;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import android.widget.Toast;

import com.android.data.DatabaseHelper;
import com.android.entities.Category;

public class CategoriesHelper {
	
	private static final String TABLE_NAME = "categories";	 
	private Context context;
	private SQLiteDatabase db;
	private DatabaseHelper openHelper;
	private SQLiteStatement insertStmt;
	private static final String INSERT = "insert into " + TABLE_NAME 
			+ "(_id, name, rate) values (?, ?, ?)";
	
	public CategoriesHelper(Context context) {
		this.context = context;
		this.openHelper = new DatabaseHelper(this.context);
		this.db = openHelper.getWritableDatabase();
		this.insertStmt = this.db.compileStatement(INSERT);
	}
	 
	public void close() {
		this.openHelper.close();
	}
	
	public long insert(String id, String name, int rate) {
		if (id != null && id.length() > 0)
			return -1;
		
		if (name != null && name.length() > 0)
			return -1;
				
		this.insertStmt.bindString(1, id);
		this.insertStmt.bindString(2, name);
		this.insertStmt.bindLong(3, rate);
		return this.insertStmt.executeInsert();
	}
	 
	public void deleteAll() {
		int result = this.db.delete(TABLE_NAME, "1", null);
		android.util.Log.i("delete", "Categories deleted: " + result);
	}
	 
	public ArrayList<Category> selectAll() {
		ArrayList<Category> list = new ArrayList<Category>();
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "_name", "rate"}, 
				null, null, null, null, "rate");
		
		if (cursor.moveToFirst()) {
			do {
				Category category = new Category(cursor.getString(1), 
						cursor.getString(2), cursor.getInt(3));
				
				list.add(category);
				
			} while (cursor.moveToNext());
		}
		
		if (cursor != null && !cursor.isClosed()) {
			cursor.close();
		}
		
		return list;
	}

	public int count() {
		int counter = 0;
		
		Cursor cursor = this.db.query(TABLE_NAME, new String[] {"_id", "name", "rate"}, 
				null, null, null, null, null);
		
		if (cursor.moveToFirst()) {
			do {
				counter++;
			} while (cursor.moveToNext());
		}

		return counter;
	}

	public void createCategory(String id, String name, int rate) {
		try {
			insert(id, name, rate);
			
		} catch (Exception e){
			e.printStackTrace();
			Toast.makeText(context, "error: " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}
	
	public void createCategory(Category c) {
		try {
			insert(c.getId(), c.getName(), c.getRate());
			
		} catch (Exception e){
			e.printStackTrace();
			Toast.makeText(context, "error: " + e.getMessage(),
					Toast.LENGTH_LONG).show();
		}
	}
		
}
